﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Example04.aspx.cs" Inherits="Chapter39.Example04" %>

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>代码清单 39-4 使用会话存储的 storage 事件</title>
    <meta name="author" content="Adam Freeman" />
    <meta name="description" content="A simple example" />
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
    <style>
        body > * {
            float: left;
        }

        table {
            border-collapse: collapse;
            margin-left: 50px;
        }

        th, td {
            padding: 4px;
        }

        input {
            border: thin solid black;
            padding: 2px;
        }

        label {
            min-width: 50px;
            display: inline-block;
            text-align: right;
        }

        #countmsg, #buttons {
            margin-left: 50px;
            margin-top: 5px;
            margin-bottom: 5px;
        }

        iframe {
            clear: left;
        }
    </style>
</head>
<body>
    <div>
        <div>
            <label for="key">Key:</label>
            <input id="key" type="text" placeholder="Enter Key" />
        </div>
        <div>
            <label for="value">Value:</label>
            <input id="value" type="text" placeholder="Enter Value" />
        </div>
        <div id="buttons">
            <button id="add">Add</button>
            <button id="clear">Clear</button>
        </div>
        <p id="countmsg">There are <span id="count">-</span> items</p>
    </div>
    <table id="data" border="1"></table>
    <iframe src="Example02.aspx" width="750" height="175"></iframe>
    <script>
        displayData();

        var buttons = document.getElementsByTagName('button');
        for (var i = 0; i < buttons.length; i++) {
            buttons[i].onclick = handleButtonPress;
        }

        function handleButtonPress(e) {
            switch (e.target.id) {
                case 'add':
                    var key = document.getElementById('key').value;
                    var value = document.getElementById('value').value;
                    sessionStorage.setItem(key, value);
                    break;

                case 'clear':
                    sessionStorage.clear();
                    break;
            }
            displayData();
        }

        function displayData() {
            var tableElem = document.getElementById('data');
            tableElem.innerHTML = '';
            var itemCount = sessionStorage.length;
            document.getElementById('count').innerHTML = itemCount;
            for (var i = 0; i < itemCount; i++) {
                var key = sessionStorage.key(i);
                var value = sessionStorage[key];
                tableElem.innerHTML += '<tr><th>' + key + '</th><td>' + value + '</td></tr>';
            }
        }
    </script>
</body>
</html>
